package cn.yanji.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.yanji.pojo.ContentRow;
import cn.yanji.service.ExcelService;
import cn.yanji.service.ExecuteService;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author yanji w2c17lin@qq.com
 * @since 2018/11/7 上午 08:56
 */
@Service
public class ExcelServiceImpl implements ExcelService {

	@Override
	public void write(String file, Map<String, List<ContentRow>> topics) throws FileNotFoundException {
		if (CollectionUtil.isEmpty(topics)) return;
		File dir = new File(ExecuteService.EXCEL_PATH);
		if (!dir.exists()) {
			//noinspection ResultOfMethodCallIgnored
			dir.mkdirs();
		}
		OutputStream outputStream = new FileOutputStream(ExecuteService.EXCEL_PATH + file);
		ExcelWriter excelWriter = new ExcelWriter(outputStream, ExcelTypeEnum.XLSX);
		int sheetNo = 1;
		for (Map.Entry<String, List<ContentRow>> topic : topics.entrySet()) {
			Sheet sheet = new Sheet(sheetNo++, 0, ContentRow.class);
			sheet.setSheetName(topic.getKey());
			excelWriter.write(topic.getValue(), sheet);
		}
		excelWriter.finish();
	}
}
